package com.lh.center.common.web.config;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.lh.center.common.base.session.SessionUser;
import com.lh.center.common.enums.LogLevel;
import com.lh.center.common.util.LoggerPrintInterceptor;
import com.lh.center.common.util.SpringUtils;
import com.lh.center.common.web.CommonWebAutoConfiguration;
import com.lh.center.common.web.session.SessionLogStorage;
import com.lh.center.common.web.session.SessionOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class BizLoggerPrintInterceptor implements LoggerPrintInterceptor {

    private CommonWebAutoConfiguration configuration;

    @Override
    public boolean isPrint(LogLevel level, Class<?> clazz, String str, Object... args) {
        if(configuration == null){
            configuration = SpringUtils.getBean(CommonWebAutoConfiguration.class);
        }
        if(configuration == null){
            return true;
        }
        if(StringUtils.isNotBlank(configuration.getLogByAssignAccount())){
            String logByAssignAccount = configuration.getLogByAssignAccount();
            //获取当前用户账号进行对比
            SessionUser user = SessionOperation.getUserNotException();
            String currentSessionUserAccount = "";
            String dubboSessionUserAccount = "";
            if(user != null){
                currentSessionUserAccount = user.getAccount();
            }
            if(SessionOperation.dubboConsumerUser.get() != null){
                dubboSessionUserAccount = SessionOperation.dubboConsumerUser.get().getAccount();
            }
            return currentSessionUserAccount.equals(logByAssignAccount) || dubboSessionUserAccount.equals(logByAssignAccount);
        }
        Set<String> logUri = new HashSet<>(configuration.getLogUri());
        logUri.add("com.lh.center.common.web.**");
        logUri.add("com.lh.center.**.mapper.**");
        PathMatcher matcher = new AntPathMatcher();
        boolean match = logUri.stream().anyMatch(uri -> matcher.match(uri, clazz.getCanonicalName()));
        if(!match){
            SessionUser user = SessionOperation.getUserNotException();
            if(user == null){
                return false;
            }
            List<SessionLogStorage> logs = SessionOperation.logs.get();
            if(CollectionUtils.isEmpty(logs)){
                SessionOperation.logs.set(new ArrayList<>());
            }
            SessionLogStorage storage = new SessionLogStorage();
            storage.setArgs(args);
            storage.setLevel(level);
            storage.setMsg(str);
            storage.setClazz(clazz);
            SessionOperation.logs.get().add(storage);
        }


        return match;
    }
}
